package app.jietuqi.cn.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;

import app.jietuqi.cn.R;

/**
 * 作者： liuyuanbo on 2018/11/20 15:29.
 * 时间： 2018/11/20 15:29
 * 邮箱： 972383753@qq.com
 * 用途： 垂直进度条
 */
public class VerticalProgressBar extends View {
    private Paint paint;// 画笔
    private int progress;// 进度值
    private int width;// 宽度值
    private int height;// 高度值
    private String mContent;

    public VerticalProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public VerticalProgressBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public VerticalProgressBar(Context context) {
        super(context);
        init();
    }

    private void init() {
        paint = new Paint();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = getMeasuredWidth() - 1;// 宽度值
        height = getMeasuredHeight() - 1;// 高度值
    }

    @Override
    protected void onDraw(Canvas canvas) {
//        paint.setColor(0x00000000);// 设置画笔颜色
        paint.setColor(ContextCompat.getColor(getContext(), R.color.alipayBlueColor));// 设置画笔颜色
        paint.setAlpha(100);
//        paint.setColor(Color.rgb(255, 255, 255));// 设置画笔颜色
//        paint.setAlpha(100);

        canvas.drawRect(0, height - progress / 100f * height, width, height, paint);// 画矩形

//        canvas.drawLine(0, 0, width, 0, paint);// 画顶边
//        canvas.drawLine(0, 0, 0, height, paint);// 画左边
//        canvas.drawLine(width, 0, width, height, paint);// 画右边
//        canvas.drawLine(0, height, width, height, paint);// 画底边

        paint.setColor(Color.BLACK);// 设置画笔颜色为红色
        paint.setTextSize(width / 5);// 设置文字大小
        if (TextUtils.isEmpty(mContent)){
            canvas.drawText(progress + "%", (width - getTextWidth(progress + "%")) / 2, height / 2, paint);// 画文字
        }else {
            canvas.drawText(mContent , (width - getTextWidth(mContent)) / 2, height / 2, paint);// 画文字
        }
        super.onDraw(canvas);
    }

    /**
     * 拿到文字宽度
     * @param str 传进来的字符串
     * return 宽度
     */
    private int getTextWidth(String str) {
        // 计算文字所在矩形，可以得到宽高
        Rect rect = new Rect();
        paint.getTextBounds(str, 0, str.length(), rect);
        return rect.width();
    }

    /** 设置progressbar进度 */
    public void setProgress(int progress) {
        this.progress = progress;
        postInvalidate();
    }
    /** 设置progressbar进度 */
    public void setText(String content) {
        this.mContent = content;
        postInvalidate();
    }
}
